const {
  RobotMessage
} = require("../model/dbmodel")
const initUrl = require("./spark")
// 添加消息
exports.insertRobotMsg = async ({ prompt: message, userId = "" }, res) => {
  res.setHeader('Content-Type', 'text/event-stream');
  message = JSON.parse(message)
  //先存用户发送消息
  if (message == "") {
    res.send({ status: 500 });
    return;
  }
  console.log(message,"message");
  //生成用户发送消息
  let msg = {
    message: message[0].content,
    userID: userId,
    time: new Date(),
    isRobot: false,
    state: 1, //消息队列
  }
  let answer
  try {
    answer = await initUrl(message, res);
  } catch (err) {
    res.send({ status: 500, err });
  }
  if(!userId){
    res.end();
  }
  let robotMessage = new RobotMessage(msg);
  robotMessage.save((err, result) => {
    if (err) {
      console.log(err);
    } else {
      //成功 开始响应答案

      new RobotMessage({
        message: answer,
        userID: userId,
        time: new Date(),
        isRobot: true,//机器人
        state: 1, //消息队列
      }).save((err, answer) => {
        if (err) {
          res.send({ status: 500, err });
        }
        res.end();
      });
    }
  })

};

exports.getMsg = (data, res) => {
  console.log(data, "getmsg data");
  let wherestr = { userID: data.id }
  RobotMessage.find(wherestr, (err, result) => {
    console.log(result, "result");
    if (err) {
      // 修改失败
      res.send({ status: 500 });
    } else {
      // 修改成功
      res.send({ status: 200, result });
    }
  })
}

